package cn.bluedot.interceptor;

import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import cn.bluedot.model.Log;
import cn.bluedot.model.User;
import cn.bluedot.service.LogManageService;

/**
 * 日志拦截器    实现Spring中的HandlerInterceptor  用于记录请求日志 
 * @author hxp
 * 2019年5月6日 上午11:10:35
 */
public class LogInterceptor  implements HandlerInterceptor{
    
    private static final ThreadLocal<Double> startTimeThreadLocal = new NamedThreadLocal<Double>("ThreadLocalStartTime");
    private static final Logger logger = Logger.getLogger(LogInterceptor.class);
    @Autowired
    LogManageService logManageService;

    /**
     * 拦截请求，在controller开始处理之前调用
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws Exception {
        
        //开始时间
        double beginTime = System.currentTimeMillis();
        //线程绑定变量 
        startTimeThreadLocal.set(beginTime);
        if(logger.isDebugEnabled()) {
            String start = "URL:"+ request.getRequestURL()+"\n开始计时："+new SimpleDateFormat("hh:mm:ss.SSS").format(beginTime);
            logger.debug(start);
        }
        return true;
    }
    
    /**
     * 当Interceptor的preHandler方法返回true时才会执行，执行时间是处理器执行之后
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView modelAndView)
            throws Exception {
        if(modelAndView!=null) {
          //记录请求视图
            logger.info("VieName:"+modelAndView.getViewName());
        }                
    }
    /**
     * 当Interceptor的preHandler方法返回true时才会执行，该方法将在整个请求完成之后，也就是DispatcherServlet渲染了视图执行
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex)
            throws Exception {        
        double beginTime = startTimeThreadLocal.get();
        double endTime = System.currentTimeMillis();
        double spendTime = endTime-beginTime;
        if(logger.isDebugEnabled()) {
            logger.debug("耗时："+(spendTime));
        }
        Date date = new Date();
        User user = (User)request.getSession().getAttribute("user");
        if(null!=user) {
            Log log = new Log(UUID.randomUUID().toString(), user.getAccount(), user.getName(),date, request.getRequestURL().toString(), request.getRequestURL().toString(),date, spendTime);
        //Log log1 = new Log(UUID.randomUUID().toString(), "username", "trueName",date, request.getRequestURL().toString(), request.getRequestURL().toString(),date, spendTime);
            logManageService.saveLogInfo(log);
        }
    }

}
